package dhm.com.dhmshop.view.home;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dhm.com.dhmshop.R;
import dhm.com.dhmshop.adapter.home.OrderDetailAdapter;
import dhm.com.dhmshop.adapter.home.OrderDetailOneAdapter;
import dhm.com.dhmshop.adapter.order.ParamTypeAdapter;
import dhm.com.dhmshop.base.BaseActiity;
import dhm.com.dhmshop.base.Presenter.PressenterImpl;
import dhm.com.dhmshop.base.netWork.Constant;
import dhm.com.dhmshop.base.netWork.LoginContract;
import dhm.com.dhmshop.entity.ShopCarBean;
import dhm.com.dhmshop.entity.UserAddr;
import dhm.com.dhmshop.entity.WacherBean;
import dhm.com.dhmshop.framework.module.commodity.entity.OneGoodsEntity;
import dhm.com.dhmshop.utils.CustomJiaJian;
import dhm.com.dhmshop.utils.SpUtils;
import dhm.com.dhmshop.view.mine.AddressActivity;

public class OrderdetailActivity extends BaseActiity implements LoginContract.IView, IWXAPIEventHandler {

    @BindView(R.id.addr_name)
    TextView addrName;
    @BindView(R.id.addr_phone)
    TextView addrPhone;
    @BindView(R.id.addr_value)
    TextView addrValue;
    @BindView(R.id.choose_addr)
    RelativeLayout chooseAddr;
    @BindView(R.id.recy)
    RecyclerView recy;
    @BindView(R.id.allprice)
    TextView allprice;
    private PressenterImpl pressenter;
    private String uid;
    private UserAddr userAddr;
    private String count;
    private String goods_param;
    private String shop_id;
    private String goods_name;
    private String price;
    private String goods_image;
    private String address_id = "";
    private PopupWindow popWindow;
    private List<ShopCarBean> allGoodsDetail;
    private String is_muti;
//    private OrderDetailAdapter orderDetailAdapter;

    OrderDetailOneAdapter orderDetailOneAdapter;
    private OneGoodsEntity oneGoodsEntit;

    @Override
    protected int getLayout() {
        return R.layout.activity_orderdetail;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        pressenter = new PressenterImpl();
        pressenter.attachView(this);
        allGoodsDetail = (List<ShopCarBean>) getIntent().getSerializableExtra("shopCarBean");
        is_muti = "0";
        uid = SpUtils.getString(OrderdetailActivity.this, "uid");
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recy.setLayoutManager(manager);
        orderDetailOneAdapter = new OrderDetailOneAdapter(this);
        recy.setAdapter(orderDetailOneAdapter);
        orderDetailOneAdapter.setShopList(allGoodsDetail);
        allprice();
    }

    private void getdetail(String gid) {

        Map<String, String> map = new HashMap<>();
        map.put("token", Constant.TOKEN);
        map.put("gid", gid + "");
        map.put("uid", uid + "");
        pressenter.sendMessage(OrderdetailActivity.this, Constant.OneGoods, map, OneGoodsEntity.class);
    }

    private void allprice() {
        double allprice=0.0;
        for (int i = 0; i < allGoodsDetail.size(); i++) {
            allprice = allprice + (Float.parseFloat(allGoodsDetail.get(i).getHeji()));
        }
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        String resultString = decimalFormat.format(allprice);
        this.allprice.setText(resultString + "");
    }

    private void getaddr() {
        Map<String, String> map = new HashMap<>();
        map.put("token", Constant.TOKEN);
        map.put("uid", uid);
        pressenter.sendMessage(OrderdetailActivity.this, Constant.GetUserAddr, map, UserAddr.class);
    }

    @Override
    protected void initData() {
        getaddr();
    }

    @Override
    public void requesta(Object data) {

        if (data instanceof UserAddr) {
            userAddr = (UserAddr) data;
            if (userAddr.getData().size() == 0) {
                Toast.makeText(this, "您还没有收货地址呦", Toast.LENGTH_SHORT).show();
            } else {
                boolean ishave = false;
                for (int i = 0; i > userAddr.getData().size(); i++) {
                    if (userAddr.getData().get(i).getTag().equals("默认")) {
                        address_id = userAddr.getData().get(i).getId() + "";
                        addrName.setText(userAddr.getData().get(i).getUser_name());
                        addrPhone.setText(userAddr.getData().get(i).getMobile());
                        addrValue.setText(userAddr.getData().get(i).getAddress());
                        ishave = true;
                    }
                }
                if (!ishave) {
                    address_id = userAddr.getData().get(0).getId() + "";
                    addrName.setText(userAddr.getData().get(0).getUser_name());
                    addrPhone.setText(userAddr.getData().get(0).getMobile());
                    addrValue.setText(userAddr.getData().get(0).getAddress());
                }
            }
        } else if (data instanceof WacherBean) {
            WacherBean orderInfo = (WacherBean) data;
            wxPay(orderInfo);
        } else if (data instanceof OneGoodsEntity) {
            OneGoodsEntity oneGoodsEntity = (OneGoodsEntity) data;
//            if (oneGoodsEntity != null || oneGoodsEntity.getData().getComment().size() > 0) {
//                oneGoodsEntit = oneGoodsEntity;
//                showPopwindow();
//            }
        }
    }

    @Override
    public void fail(String error) {

    }

    @OnClick({R.id.eitegoods_fan, R.id.commit_order, R.id.choose_addr})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.eitegoods_fan:
                finish();
                break;
            case R.id.choose_addr:
                Intent intent = new Intent(OrderdetailActivity.this, AddressActivity.class);
                intent.putExtra("type", 1);
                startActivityForResult(intent, 200);


                break;
            case R.id.commit_order:
                if (address_id == null || address_id.equals("") || address_id.equals("0")) {
                    Toast.makeText(this, "请选择地址", Toast.LENGTH_SHORT).show();
                    return;
                }
                Map<String, String> map = new HashMap<>();
                map.put("uid", uid);
                map.put("s_addressId", address_id);
                map.put("payType", "1");
                map.put("totalMoney", allprice.getText().toString());
                map.put("payFrom",2+"");
                map.put("token", Constant.TOKEN);

                pressenter.sendMessage(OrderdetailActivity.this, Constant.CreatOrder, map, WacherBean.class);
                break;
            default:
        }
    }

    private void wxPay(WacherBean wacherBean) {
        IWXAPI api = WXAPIFactory.createWXAPI(OrderdetailActivity.this, Constant.Wx_APP_ID);
        api.handleIntent(getIntent(), this);
        api.registerApp(Constant.Wx_APP_ID);
        PayReq req = new PayReq();
        req.appId = wacherBean.getAppid();
        req.partnerId = wacherBean.getPartnerid();
        req.prepayId = wacherBean.getPrepayid();
        req.packageValue = wacherBean.getPackageX();
        req.nonceStr = wacherBean.getNoncestr();
        req.timeStamp = wacherBean.getTimestamp();
        req.sign = wacherBean.getSign();
        api.sendReq(req);

    }


    @Override
    public void onReq(BaseReq baseReq) {

    }

    final String TAG = "onResp";

    @Override
    public void onResp(BaseResp resp) {
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {

            switch (resp.errCode) {
                case 0://支付成功
                    Toast.makeText(this, "支付成功", Toast.LENGTH_SHORT).show();
                    break;
                case -1://错误，可能的原因：签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等
                    Toast.makeText(this, "支付错误" + resp.errCode, Toast.LENGTH_SHORT).show();
                    break;
                case -2://用户取消，无需处理。发生场景：用户不支付了，点击取消，返回APP。
                    Toast.makeText(this, "用户取消" + resp.errCode, Toast.LENGTH_SHORT).show();
                    break;
                    default:
                        Toast.makeText(this, "支付失败" + resp.errCode, Toast.LENGTH_SHORT).show();
                        break;
            }
            finish();//这里需要关闭该页面
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 200:
                if (resultCode == RESULT_OK) {
                    address_id = data.getIntExtra("address_id", 0) + "";
                    if (!address_id.equals("0")) {
                        String name = data.getStringExtra("name");
                        String phone = data.getStringExtra("phone");
                        String address = data.getStringExtra("address");
                        addrName.setText(name);
                        addrPhone.setText(phone);
                        addrValue.setText(address);
                    }


                }
                break;
            default:
        }
    }


    private String goods_formats = "";
    private int num = 1;
    private int position = 0;

    private void showPopwindow() {
        View popView = View.inflate(OrderdetailActivity.this, R.layout.popup_param, null);
        ImageView cancle = popView.findViewById(R.id.cancle);
        SimpleDraweeView image = popView.findViewById(R.id.image);
        TextView commde_price = popView.findViewById(R.id.commde_price);
        TextView param = popView.findViewById(R.id.param);
        RecyclerView recy = popView.findViewById(R.id.recy);
        Button sure = popView.findViewById(R.id.sure);
        CustomJiaJian jiajian = popView.findViewById(R.id.jiajian);
        jiajian.setCustomListener(new CustomJiaJian.CustomListener() {
            @Override
            public void jiajian(int count) {
                num = count;
//                commde_price.setText(count*Float.parseFloat(oneGoodsEntit.getData().getExpress_price())+"");
            }

            @Override
            public void shuRuZhi(int count) {
                num = count;
//                commde_price.setText(count*Float.parseFloat(oneGoodsEntit.getData().getExpress_price())+"");
            }
        });

        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popWindow.dismiss();
            }
        });
/*
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goods_formats = "";
//                for (int i=0;i<oneGoodsEntit.getData().getParam().size();i++){
//                    for (int j=0;j<oneGoodsEntit.getData().getParam().get(i).getParam_value().size();j++){
//                        if (oneGoodsEntit.getData().getParam().get(i).getParam_check().get(j).equals("1")){
//                            goods_formats=goods_formats+oneGoodsEntit.getData().getParam().get(i).getParam_value().get(j)+",";
//                        }
//                    }
//                }
                allGoodsDetail.get(position).setCount(num + "");
                allprice();
                if (goods_formats.equals("")) {
                    Toast.makeText(OrderdetailActivity.this, "请选择商品规格", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    goods_formats = goods_formats.substring(0, goods_formats.length() - 1);
                    allGoodsDetail.get(position).setGoods_param(goods_formats);
                }

                orderDetailAdapter.setShopList(allGoodsDetail);
                popWindow.dismiss();
            }
        });
*/

//        commde_price.setText(oneGoodsEntit.getData().getExpress_price());
//        image.setImageURI(Constant.PATH+"/"+oneGoodsEntit.getData().getGoods_images_thumb());
        LinearLayoutManager manager = new LinearLayoutManager(OrderdetailActivity.this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
//        jiajian.setEditText(Integer.parseInt(allGoodsDetail.get(position).getCount()));
        recy.setLayoutManager(manager);
        ParamTypeAdapter paramTypeAdapter = new ParamTypeAdapter(OrderdetailActivity.this);
        paramTypeAdapter.setaddClick(new ParamTypeAdapter.OnIntentClick() {
            @Override
            public void item(int posttion, int childposttion) {
//                for (int j=0;j<oneGoodsEntit.getData().getParam().get(posttion).getParam_value().size();j++){
//                    oneGoodsEntit.getData().getParam().get(posttion).getParam_check().set(j,"0");
//                }
//                oneGoodsEntit.getData().getParam().get(posttion).getParam_check().set(childposttion,"1");
//                String yixuan="已选：";
//                for (int i=0;i<oneGoodsEntit.getData().getParam().size();i++){
//                    for (int j=0;j<oneGoodsEntit.getData().getParam().get(i).getParam_value().size();j++){
//                        if (oneGoodsEntit.getData().getParam().get(i).getParam_check().get(j).equals("1")){
//                            yixuan=yixuan+" '"+oneGoodsEntit.getData().getParam().get(i).getParam_value().get(j)+"'";
//                        }else {
//                        }
//                    }
//                }
//                param.setText(yixuan);
//                paramTypeAdapter.setImageList(oneGoodsEntit.getData().getParam());
            }
        });
        recy.setAdapter(paramTypeAdapter);
//        if (oneGoodsEntit.getData().getParam()!=null){
//            for (int i=0;i<oneGoodsEntit.getData().getParam().size();i++){
//                List<String> check=new ArrayList<>();
//                for (int j=0;j<oneGoodsEntit.getData().getParam().get(i).getParam_value().size();j++){
//                    check.add("0");
//                }
//                oneGoodsEntit.getData().getParam().get(i).setParam_check(check);
//            }
//
//        }

//        if (oneGoodsEntit.getData().getParam()==null){
//            Toast.makeText(OrderdetailActivity.this, "该商品信息还未完善", Toast.LENGTH_SHORT).show();
//        }else {
//            paramTypeAdapter.setImageList(oneGoodsEntit.getData().getParam());
//        }

        popWindow = new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popWindow.setAnimationStyle(R.style.AnimBottom);
        popWindow.setFocusable(true);
        popWindow.setTouchable(true);
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        popWindow.setOutsideTouchable(true);// 设置允许在外点击消失

        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // popupWindow隐藏时恢复屏幕正常透明度
                setBackgroundAlpha(1.0f);
            }
        });


        setBackgroundAlpha(0.5f);
        popWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 0);


    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha 屏幕透明度0.0-1.0 1表示完全不透明
     */
    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = OrderdetailActivity.this.getWindow()
                .getAttributes();
        lp.alpha = bgAlpha;
        OrderdetailActivity.this.getWindow().setAttributes(lp);
    }

}
